﻿using System;
using System.Collections.ObjectModel;
using Heimdallr.Async;

namespace Heimdallr.Net
{
    internal class ResponseWrapper<TMission>
    {
        #region Field

        private readonly QueueConsumer<TMission> queue; 
        private readonly HttpResponseContext response;
        private readonly MissionCallback<TMission> missionCallback;
        private readonly Guid id;
         
        #endregion

        #region Property
         
        public Guid ID
        {
            get { return this.id; }
        }

        public HttpResponseContext Response
        {
            get { return this.response; }
        }
         
        public bool IsClosed
        {
            get { return this.response.IsDisposed; }
        }

        #endregion
         
        #region Constructor

        public ResponseWrapper(HttpResponseContext response, MissionCallback<TMission> missionCallback)
        {
            this.queue = new QueueConsumer<TMission>(this.PublishCallback);
            this.response = response;
            this.missionCallback = missionCallback;
            this.id = Guid.NewGuid(); 
        }

        #endregion

        #region Method

        public void PublishAsync(TMission mission)
        {
            this.queue.EnqueueAndStart(mission);
        }
          
        public void Close()
        {
            this.response.Dispose();
        }

        #endregion

        #region Callback

        private void PublishCallback(TMission mission)
        {
            this.missionCallback(this, mission);
        }
         
        #endregion 
    }
     
    internal delegate void MissionCallback<TMission>(ResponseWrapper<TMission> wrapper, TMission mission);
     
    internal class ResponseWrapperCollection<TMission> : KeyedCollection<Guid, ResponseWrapper<TMission>>
    {
        protected override Guid GetKeyForItem(ResponseWrapper<TMission> item)
        {
            return item.ID;
        }
    }
}
